package com.hmall.trade.listener;

import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 支付状态监听组件
 * 监听支付服务发送的支付结果消息，处理订单状态更新
 */
@Component
@RequiredArgsConstructor
public class PayStatusListener {

    private final IOrderService orderService;

    /**
     * 监听支付成功消息
     * 当收到支付成功消息时，将对应订单状态更新为"已支付"
     *
     * @param orderId 订单ID
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.pay.success.queue", durable = "true"),
            exchange = @Exchange(name = "pay.topic", type = "topic"),
            key = "pay.success"
    ))
    public void listenPaySuccess(Long orderId) {

        // 1. 查询订单信息
        Order order = orderService.getById(orderId);

        // 2. 校验订单有效性和状态
        // 仅处理存在且状态为1即未支付的订单
        if (order == null || order.getStatus() != 1) {
            // 订单不存在或状态已变更，直接返回
            return;
        }

        // 3. 调用服务层方法标记订单为支付成功
        // 此方法应包含订单状态更新、库存扣减、积分增加等业务逻辑
        orderService.markOrderPaySuccess(orderId);
    }
}